package com.hds.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.hds.common.exception.RRException;
import com.hds.common.utils.PageUtils;
import com.hds.common.utils.R;
import com.hds.common.validator.Assert;
import com.hds.modules.app.annotation.Login;
import com.hds.modules.app.annotation.LoginUser;
import com.hds.modules.app.entity.UserEntity;
import com.hds.modules.app.service.UserService;
import com.hds.modules.sys.controller.AbstractController;
import com.hds.modules.sys.entity.base.SysMemberShipEntity;
import com.hds.modules.sys.entity.base.SysMemberShipRecordsEntity;
import com.hds.modules.sys.service.base.SysMemberShipRecordsService;
import com.hds.modules.sys.service.base.SysMemberShipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author guonan
 * @Email guonan@yewcn.com
 * @Description 会员
 * @Date 2018/6/12 14:13
 */
@RestController
@RequestMapping("/app/membership/records/")
public class AppMemberShipRecordsController extends AbstractController{


    @Autowired
    private SysMemberShipRecordsService sysMemberShipRecordsService;

    @Autowired
    private SysMemberShipService sysMemberShipService;

    @Autowired
    private UserService userService;

    @Login
    @GetMapping("/list")
    public R list(@LoginUser UserEntity user, @RequestParam Map<String, Object> params){
        logger.info("当前用户id:{}", user.getUserId());
        params.put("uid", String.valueOf(user.getUserId()));
        PageUtils page = sysMemberShipRecordsService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 查询会员升级记录详情
     * @param user
     * @param id
     * @return
     */
    @Login
    @GetMapping("/{id}")
    public R get(@LoginUser UserEntity user, @PathVariable Integer id){
        Assert.isNull(id,"id不能为空");
        SysMemberShipEntity sysMemberShipEntity = null;
        SysMemberShipRecordsEntity sysMemberShipRecords = sysMemberShipRecordsService.selectById(id);
        if(sysMemberShipRecords != null){
            sysMemberShipEntity = sysMemberShipService.selectById(sysMemberShipRecords.getLevelId());
        }
        sysMemberShipRecords.setSysMemberShip(sysMemberShipEntity);
        return R.ok().put("data", sysMemberShipRecords);
    }




    /**
     *
     * @param user
     * @param sysMemberShipRecords levelId ,
     * @return
     */
    @Transactional
    @Login
    @PostMapping("/save")
    public R save(@LoginUser UserEntity user, @RequestBody SysMemberShipRecordsEntity sysMemberShipRecords) throws RRException{
        logger.info("=====【新增会员升级记录】传入的入参报文=====:{}", JSONObject.toJSON(sysMemberShipRecords));
        Assert.isNull(sysMemberShipRecords, "内容不能为空");
        sysMemberShipRecords.setUid(user.getUserId());

        Integer id = sysMemberShipRecords.getId();
        Integer resultOrderId = null;
        Boolean b = null;
        try {
            if(id == null){
                Integer levelId = sysMemberShipRecords.getLevelId();
                Assert.isNull(levelId, "请输入会员升级levelId");
                SysMemberShipEntity sysMemberShip = sysMemberShipService.queryByLevel(levelId);
                logger.info("=====【会员升级新增订单】sysMemberShip:{}", JSONObject.toJSON(sysMemberShip));

                if(sysMemberShip == null){
                    throw new RRException("未找到改会员权益信息，注意查看levelId是否填写正确");
                }


                // 如果该用户的该会员等级还有未支付订单，则不生成新订单
                Map<String, Object> map = new HashMap<>();
                map.put("uid", user.getUserId());
                map.put("level_id", levelId);
                map.put("status", SysMemberShipRecordsEntity.NOSUCCESS);
                List<SysMemberShipRecordsEntity> records = sysMemberShipRecordsService.selectByMap(map);

                // 有未支付订单
                if(records != null && records.size() > 0) {
                    SysMemberShipRecordsEntity record = records.get(0);
                    return R.ok().put("orderId", record.getId());
                }


                BigDecimal currVipPtice = sysMemberShip.getPrice();
                sysMemberShipRecords.setPayAmount(currVipPtice.toString());
                sysMemberShipRecords.setRealAmount(currVipPtice.toString());

                logger.info("=====【会员升级新增订单】开始请求 - 入参报文=====:{}", JSONObject.toJSON(sysMemberShipRecords));
                resultOrderId = sysMemberShipRecordsService.save(sysMemberShipRecords);
                logger.info("=====resultOrderId=====:{}", resultOrderId);
                if(resultOrderId == null) {
                    return R.error("生成新订单失败");
                }
                return R.ok().put("orderId", resultOrderId);
            }else{
                // 支付成功才更新，否则不更新订单
                SysMemberShipRecordsEntity sysMemberShipRecordsEntity  = sysMemberShipRecordsService.selectById(id);
                resultOrderId = sysMemberShipRecordsEntity.getId();
                if(sysMemberShipRecordsEntity == null){
                    throw new RRException("未找到改会员权益记录，注意查看id是否填写正确");
                }
                sysMemberShipRecordsEntity.setStatus(SysMemberShipRecordsEntity.SUCCESS);
                b = sysMemberShipRecordsService.update(sysMemberShipRecordsEntity);
                if(b) {
                    Boolean r = this.updateMemberShipCurrUser(user, resultOrderId);
                    return r ? R.ok("更新成功").put("orderId", resultOrderId) : R.error("订单更新失败");
                }
                return R.error("订单更新失败");
            }
        } catch (Exception e) {
            logger.info("====会员升级过程出现异常，请联系管理员====:{}", e.getMessage());
            throw new RRException("会员升级过程出现异常，请联系管理员");
        }
    }


    // 更新该用户的会员权益（等级）
    public Boolean updateMemberShipCurrUser (UserEntity user, Integer id) throws RRException{
        SysMemberShipRecordsEntity record = sysMemberShipRecordsService.selectById(id);
        user.setLevelId(record.getLevelId());
        return userService.updateById(user);
    }




}
